package com.insight.modules.system.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.insight.modules.constant.CommonConstant;
import com.insight.modules.system.entity.*;
import com.insight.modules.system.service.*;
import com.yuanqiao.insight.common.constant.CommonConstant;
import com.yuanqiao.insight.common.util.common.LocalCacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.insight.modules.system.entity.*;
import org.insight.modules.system.service.*;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.system.query.QueryGenerator;
import com.insight.common.system.vo.LoginUser;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.system.entity.*;
import com.insight.modules.system.model.TreeModel;
import com.insight.modules.system.service.*;
import com.insight.modules.umpPwdManage.entity.UmpPwdManage;
import com.insight.modules.umpPwdManage.service.IUmpPwdManageService;
import com.insight.modules.util.ZipEncryUtils;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-19
 */
@RestController
@RequestMapping("/sys/role")
@Slf4j
public class SysRoleController {
    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysPermissionDataRuleService sysPermissionDataRuleService;

    @Autowired
    private ISysRolePermissionService sysRolePermissionService;

    @Autowired
    private ISysPermissionService sysPermissionService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUmpPwdManageService umpPwdManageService;
    @Autowired
    private ZipEncryUtils zipEncryUtils;
    @Autowired
    private ISysThreePowerMenuService sysThreePowerMenuService;

    private static final LocalCacheUtils cacheUtils = LocalCacheUtils.getInstance();
    //    @Value("${insight.isThreePowers}")
    private Integer isThreePowers;

    /**
     * 分页列表查询
     *
     * @param role
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "角色管理-分页列表查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<SysRole>> queryPageList(SysRole role,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {

        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(role.getRoleName())) {
            queryWrapper.like("role_name", role.getRoleName());
        }
        isThreePowers = Integer.valueOf((String) cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "insight_threePowers_isEnable"));
        if (1 == isThreePowers) {
            queryWrapper.ne("role_code", CommonConstant.ADMIN);
        }
        if (StringUtils.isNotEmpty(role.getRoleCode())){
            String[] split = role.getRoleCode().split(",");
            queryWrapper.in("role_code", Arrays.asList(split));
        }
        queryWrapper.orderByDesc("create_time");
        Result<IPage<SysRole>> result = new Result<IPage<SysRole>>();
        Page<SysRole> page = new Page<SysRole>(pageNo, pageSize);
        IPage<SysRole> pageList = sysRoleService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 获取加锁用户列表数据
     *
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "用户解锁-分页显示")
    @RequestMapping(value = "/list2", method = RequestMethod.GET)
    public Result<IPage<SysUsers>> queryPageList(SysUsers user, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<SysUsers> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(user.getRoleName())) {
            queryWrapper.like("username", user.getRoleName());
        }
        queryWrapper.eq("locks", 1);
        Result<IPage<SysUsers>> result = new Result<>();
        Page<SysUsers> page = new Page<>(pageNo, pageSize);
        IPage<SysUsers> pageList = sysUserService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 解锁
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/updateLock", method = RequestMethod.POST)
    //@RequiresRoles({"admin"})
    public Result<SysUsers> updateLock(@RequestBody SysUsers user) {
        Result<SysUsers> result = new Result<>();
        QueryWrapper<SysUsers> queryWrapper = new QueryWrapper<>();
        try {
            if (user == null || user.getId() == null) {
                result.error500("用户ID不能为空");
                return result;
            }
            queryWrapper.eq("id", user.getId());
            if (sysUserService == null) {
                result.error500("服务不可用");
                return result;
            }
            SysUsers one = sysUserService.getOne(queryWrapper);
            if (one == null) {
                result.error500("未找到用户");
                return result;
            }
            String key = "locks:" + one.getUsername();
            one.setLocks(0);
            sysUserService.updateById(one);
            if (redisTemplate != null && redisTemplate.hasKey(key)) {
                redisTemplate.opsForValue().set(key, 0);
            }
            result.setSuccess(true);
            result.setCode(200);
        } catch (Exception e) {
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("解锁失败");
            return result;
        }
        return result;
    }


    /**
     * 添加
     *
     * @param role
     * @return
     */
    @RequiresPermissions("role:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    //@RequiresRoles({"admin"})
    public Result<SysRole> add(@RequestBody SysRole role) {
        Result<SysRole> result = new Result<SysRole>();
        try {
            if (role == null) {
                result.error500("参数不能为空");
                return result;
            }
            role.setCreateTime(new Date());
            if (sysRoleService == null) {
                result.error500("服务不可用");
                return result;
            }
            sysRoleService.save(role);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param role
     * @return
     */
    @AutoLog(value = "角色管理-编辑")
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<SysRole> edit(@RequestBody SysRole role) {
        Result<SysRole> result = new Result<SysRole>();
        SysRole sysrole = sysRoleService.getById(role.getId());
        if (sysrole == null) {
            result.error500("未找到对应实体");
        } else {
            role.setUpdateTime(new Date());
            boolean ok = sysRoleService.updateById(role);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "角色管理-删除")
    //@RequiresRoles({"admin"})
    @RequiresPermissions("role:del")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        isThreePowers = Integer.valueOf((String) cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "insight_threePowers_isEnable"));
        if (1 == isThreePowers) {
            SysRole role = sysRoleService.getById(id);
            if (getThreePowersRole().contains(role.getRoleCode())) {
                return Result.error(role.getRoleName() + "角色不允许删除,请选择其他角色！");
            }
        }
        boolean b = sysRoleService.deleteRole(id);
        if (!b) {
            return Result.error("删除失败!");
        }
        return Result.ok("删除角色成功");
    }

//    public static void main(String[] args) {
//        String SMROLE = "root,secadm,auditadm";
//        System.out.println(SMROLE.contains("admin"));
//    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<SysRole> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<SysRole> result = new Result<SysRole>();
        if (oConvertUtils.isEmpty(ids)) {
            result.error500("未选中角色！");
        } else {
            isThreePowers = Integer.valueOf((String) cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "insight_threePowers_isEnable"));
            if (1 == isThreePowers) {
                List<SysRole> roles = sysRoleService.listByIds(Arrays.asList(ids.split(",")));
                for (SysRole role : roles) {
                    if (getThreePowersRole().contains(role.getRoleCode())) {
                        Result.error(role.getRoleName() + "角色不允许删除,请重新选择！");
                    }
                }

            }
            boolean b = sysRoleService.deleteBatchRole(ids.split(","));
            if (!b) {
                result.error500("删除角色失败！");
            }
            result.success("删除角色成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<SysRole> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<SysRole> result = new Result<SysRole>();
        SysRole sysrole = sysRoleService.getById(id);
        if (sysrole == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysrole);
            result.setSuccess(true);
        }
        return result;
    }

    @GetMapping(value = "/queryall")
    public Result<List<SysRole>> queryall(@RequestParam(required = false, defaultValue = "") String username) {
        Result<List<SysRole>> result = new Result<>();
        isThreePowers = Integer.valueOf((String) cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "insight_threePowers_isEnable"));
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (1 == isThreePowers) {
            int exclusionRole = Integer.parseInt((String) cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "insight_threePowers_exclusionRole"));
            List<String> threePowersRole = new ArrayList<>();
            threePowersRole.add("admin");
            if (exclusionRole == 1 && !SysUserController.getThreePowers().contains(username)) {
                threePowersRole = getThreePowersRole();
            }
            lambdaQueryWrapper.notIn(SysRole::getRoleCode, threePowersRole);
        }
        List<SysRole> list = sysRoleService.list(lambdaQueryWrapper);
        if (list == null || list.size() <= 0) {
            result.error500("未找到角色信息");
        } else {
            result.setResult(list);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 校验角色编码唯一
     */
    @RequestMapping(value = "/checkRoleCode", method = RequestMethod.GET)
    public Result<Boolean> checkUsername(String id, String roleCode) {
        Result<Boolean> result = new Result<>();
        result.setResult(true);
        log.info("--验证角色编码是否唯一---id:" + id + "--roleCode:" + roleCode);
        try {
            SysRole role = null;
            if (oConvertUtils.isNotEmpty(id)) {
                if (sysRoleService == null) {
                    result.setSuccess(false);
                    result.setMessage("服务不可用");
                    return result;
                }
                role = sysRoleService.getById(id);
            }
            if (sysRoleService == null) {
                result.setSuccess(false);
                result.setMessage("服务不可用");
                return result;
            }
            QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SysRole::getRoleCode, roleCode);
            SysRole newRole = sysRoleService.getOne(queryWrapper);
            if (newRole != null) {
                if (role == null) {
                    result.setSuccess(false);
                    result.setMessage("角色编码已存在");
                    return result;
                } else if (!id.equals(newRole.getId())) {
                    result.setSuccess(false);
                    result.setMessage("角色编码已存在");
                    return result;
                }
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResult(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     */
    @AutoLog(value = "角色管理-导出")
    @RequestMapping(value = "/exportXls")
//	public ModelAndView exportXls(SysRole sysRole, HttpServletRequest request) {
//		// Step.1 组装查询条件
//		QueryWrapper<SysRole> queryWrapper = QueryGenerator.initQueryWrapper(sysRole, request.getParameterMap());
//		//Step.2 AutoPoi 导出Excel
//		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//		List<SysRole> pageList = sysRoleService.list(queryWrapper);
//		//导出文件名称
//		mv.addObject(NormalExcelConstants.FILE_NAME,"角色列表");
//		mv.addObject(NormalExcelConstants.CLASS,SysRole.class);
//		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		mv.addObject(NormalExcelConstants.PARAMS,new ExportParams("角色列表数据","导出人:"+user.getRealname(),"导出信息"));
//		mv.addObject(NormalExcelConstants.DATA_LIST,pageList);
//		return mv;
//	}

    public void exportXls(SysRole sysRole, HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<SysRole> queryWrapper = QueryGenerator.initQueryWrapper(sysRole, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
//		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysRole> pageList = sysRoleService.list(queryWrapper);
        // 过滤选中数据
        List<SysRole> exportList = new ArrayList<>();
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            for (SysRole role : pageList) {
                String id = role.getId();
                for (String idFront : selections.split(",")) {
                    if (idFront.equals(id)){
                        exportList.add(role);
                    }
                }
            }
        } else {
            exportList = pageList;
        }

        UmpPwdManage zip = umpPwdManageService.getZip();
        String fileName = umpPwdManageService.exportXlsRename("角色管理");
        zipEncryUtils.zipPwd(response, SysRole.class, fileName, zip.getZipPwd(), zip.getIsEncry(), exportList);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest != null ? multipartRequest.getFileMap() : null;
        if (fileMap == null || fileMap.isEmpty()) {
            return Result.error("文件导入失败！");
        }
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();
            if (file == null) {
                continue;
            }
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                if (sysRoleService == null) {
                    return Result.error("服务不可用");
                }
                return sysRoleService.importExcelCheckRoleCode(file, params);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 查询数据规则数据
     */
    @GetMapping(value = "/datarule/{permissionId}/{roleId}")
    public Result<?> loadDatarule(@PathVariable("permissionId") String permissionId, @PathVariable("roleId") String roleId) {
        List<SysPermissionDataRule> list = sysPermissionDataRuleService.getPermRuleListByPermId(permissionId);
        if (list == null || list.size() == 0) {
            return Result.error("未找到权限配置信息");
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("datarule", list);
            LambdaQueryWrapper<SysRolePermission> query = new LambdaQueryWrapper<SysRolePermission>()
                    .eq(SysRolePermission::getPermissionId, permissionId)
                    .isNotNull(SysRolePermission::getDataRuleIds)
                    .eq(SysRolePermission::getRoleId, roleId);
            SysRolePermission sysRolePermission = sysRolePermissionService.getOne(query);
            if (sysRolePermission == null) {
                //return Result.error("未找到角色菜单配置信息");
            } else {
                String drChecked = sysRolePermission.getDataRuleIds();
                if (oConvertUtils.isNotEmpty(drChecked)) {
                    map.put("drChecked", drChecked.endsWith(",") ? drChecked.substring(0, drChecked.length() - 1) : drChecked);
                }
            }
            return Result.ok(map);
            //TODO 以后按钮权限的查询也走这个请求 无非在map中多加两个key
        }
    }

    /**
     * 保存数据规则至角色菜单关联表
     */
    @PostMapping(value = "/datarule")
    public Result<?> saveDatarule(@RequestBody JSONObject jsonObject) {
        try {
            if (jsonObject == null) {
                return Result.error("请求数据不能为空");
            }
            String permissionId = jsonObject.getString("permissionId");
            String roleId = jsonObject.getString("roleId");
            String dataRuleIds = jsonObject.getString("dataRuleIds");
            log.info("保存数据规则>>" + "菜单ID:" + permissionId + "角色ID:" + roleId + "数据权限ID:" + dataRuleIds);
            if (permissionId == null || roleId == null) {
                return Result.error("菜单ID或角色ID不能为空");
            }
            LambdaQueryWrapper<SysRolePermission> query = new LambdaQueryWrapper<SysRolePermission>()
                    .eq(SysRolePermission::getPermissionId, permissionId)
                    .eq(SysRolePermission::getRoleId, roleId);
            if (sysRolePermissionService == null) {
                return Result.error("服务不可用");
            }
            SysRolePermission sysRolePermission = sysRolePermissionService.getOne(query);
            if (sysRolePermission == null) {
                return Result.error("请先保存角色菜单权限!");
            } else {
                sysRolePermission.setDataRuleIds(dataRuleIds);
                this.sysRolePermissionService.updateById(sysRolePermission);
            }
        } catch (Exception e) {
            log.error("SysRoleController.saveDatarule()发生异常：" + e.getMessage(), e);
            return Result.error("保存失败");
        }
        return Result.ok("保存成功!");
    }


    /**
     * 用户角色授权功能，查询菜单权限树
     *
     * @return
     */
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public Result<Map<String, Object>> queryTreeList(@RequestParam(name = "roleId") String roleId, @RequestParam(name = "platformType", required = false) Integer platformType) {

        SysRole role = sysRoleService != null ? sysRoleService.getById(roleId) : null;

        Result<Map<String, Object>> result = new Result<>();
        List<String> ids = new ArrayList<>();
        try {
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
            query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);

            if (cacheUtils != null && sysRoleService != null && sysThreePowerMenuService != null) {
                try {
                    String cacheValue = (String) cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "insight_threePowers_isEnable");
                    isThreePowers = cacheValue != null ? Integer.parseInt(cacheValue) : 0;
                } catch (NumberFormatException e) {
                    isThreePowers = 0;
                }

                if (1 == isThreePowers && role != null) {
                    if (!CommonConstant.ADMIN.equals(role.getRoleCode())) {
                        if (getRoleAuditadm().contains(role.getRoleCode()) || getRoleSecadm().contains(role.getRoleCode())) {
                            List<SysThreePowerMenu> sysThreePowerMenus = sysRoleService.getSysThreepowerMenueByRoleCode(role.getRoleCode());
                            if (sysThreePowerMenus != null && !sysThreePowerMenus.isEmpty()) {
                                List<String> sysThreePowerMenuPerIds = sysThreePowerMenus.stream()
                                        .map(SysThreePowerMenu::getPremissionId)
                                        .filter(id -> id != null)
                                        .collect(Collectors.toList());
                                if (!sysThreePowerMenuPerIds.isEmpty()) {
                                    query.in(SysPermission::getId, sysThreePowerMenuPerIds);
                                }
                            }
                        } else if (getRoleRoot().contains(role.getRoleCode())) {
                            List<SysThreePowerMenu> sysThreePowerMenus = sysThreePowerMenuService.list(
                                    new LambdaQueryWrapper<SysThreePowerMenu>()
                                            .ne(SysThreePowerMenu::getRoleCode, "other")
                                            .eq(SysThreePowerMenu::getShowType, "1"));
                            if (sysThreePowerMenus != null && !sysThreePowerMenus.isEmpty()) {
                                List<String> perIds = sysThreePowerMenus.stream()
                                        .map(SysThreePowerMenu::getPremissionId)
                                        .filter(id -> id != null)
                                        .collect(Collectors.toList());
                                if (!perIds.isEmpty()) {
                                    query.notIn(SysPermission::getId, perIds);
                                }
                            }
                        } else {
                            List<SysThreePowerMenu> sysThreePowerMenus = sysThreePowerMenuService.list(
                                    new LambdaQueryWrapper<SysThreePowerMenu>()
                                            .eq(SysThreePowerMenu::getShowType, "1"));
                            if (sysThreePowerMenus != null && !sysThreePowerMenus.isEmpty()) {
                                List<String> perIds = sysThreePowerMenus.stream()
                                        .map(SysThreePowerMenu::getPremissionId)
                                        .filter(id -> id != null)
                                        .collect(Collectors.toList());
                                if (!perIds.isEmpty()) {
                                    query.notIn(SysPermission::getId, perIds);
                                }
                            }
                        }
                    }
                }
            }

            if (platformType != null) {
                query.eq(SysPermission::getPlatformType, platformType);
            }
            query.orderByAsc(SysPermission::getSortNo);

            List<SysPermission> list = sysPermissionService != null ? sysPermissionService.list(query) : new ArrayList<>();
            if (list != null) {
                for (SysPermission sysPer : list) {
                    if (sysPer != null && sysPer.getId() != null) {
                        ids.add(sysPer.getId());
                    }
                }
            }
            List<TreeModel> treeList = getMenuList(list);
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("treeList", treeList);//全部树节点数据
            resMap.put("ids", ids);//全部树ids
            result.setResult(resMap);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("查询失败");
        }
        return result;
    }

    @GetMapping("/hasButtonRole")
    public Result<?> hasButtonRole(@RequestParam("role") String role, @RequestParam(value = "userId", required = false) String userId) {
        if (StringUtils.isEmpty(userId)) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            userId = sysUser.getId();
        }
        return Result.OK(sysRoleService.hasButtonRole(role, userId));
    }

    //获得树级结构菜单
    public List<TreeModel> getMenuList(List<SysPermission> list) {
        //拿到菜单的所有数据
        //存储根节点的菜单，即一级菜单
        List<TreeModel> treeList = new ArrayList<>();
        //遍历所有数据，找到根节点菜单
        for (SysPermission permission : list) {
            TreeModel tree = new TreeModel(permission.getId(), permission.getParentId(), permission.getName(), permission.getRuleFlag(), permission.isLeaf());
            if (StringUtils.isEmpty(tree.getParentId())) {
                //找到根节点菜单的时候，寻找这个根节点菜单下的子节点菜单。
                findChilds(tree, list);
                //添加到根节点的列表中
                treeList.add(tree);
            }
        }
        return treeList;
    }

    private void findChilds(TreeModel root, List<SysPermission> list) {
        List<TreeModel> childlist = new ArrayList<>();
        //遍历所有数据，找到是入参父节点的子节点的数据，然后加到childlist集合中。
        for (SysPermission permission : list) {
            TreeModel tree = new TreeModel(permission.getId(), permission.getParentId(), permission.getName(), permission.getRuleFlag(), permission.isLeaf());
            if (root.getKey().equals(tree.getParentId()))
                childlist.add(tree);
        }
        //若子节点不存在，那么就不必再遍历子节点中的子节点了 直接返回。
        if (childlist.size() == 0)
            return;
        //设置父节点的子节点列表
        root.setChildren(childlist);
        //若子节点存在，接着递归调用该方法，寻找子节点的子节点。
        for (TreeModel childs : childlist) {
            findChilds(childs, list);
        }
    }

    private void getTreeModelList(List<TreeModel> treeList, List<SysPermission> metaList, TreeModel temp) {
        for (SysPermission permission : metaList) {
            String tempPid = permission.getParentId();
            TreeModel tree = new TreeModel(permission.getId(), tempPid, permission.getName(), permission.getRuleFlag(), permission.isLeaf());
            if (temp == null && oConvertUtils.isEmpty(tempPid)) {
                treeList.add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getKey())) {
                temp.getChildren().add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            }

        }
    }

    public static List<String> getThreePowersRole() {
        List<String> threePowersRole = new ArrayList<>();
        threePowersRole.addAll(getRoleRoot());
        threePowersRole.addAll(getRoleAuditadm());
        threePowersRole.addAll(getRoleSecadm());
        threePowersRole.add("admin");
        return threePowersRole;
    }

    public static List<String> getRoleRoot() {
        String threePowersKey = CommonConstant.DATA_DICT_KEY + "insight_threePowers";
        String roleRoot = String.valueOf(cacheUtils.getValueByKey((threePowersKey + "_roleRoot")));
        return new ArrayList<>(Arrays.asList(roleRoot.split(",")));
    }

    public static List<String> getRoleAuditadm() {
        String threePowersKey = CommonConstant.DATA_DICT_KEY + "insight_threePowers";
        String roleAuditadm = String.valueOf(cacheUtils.getValueByKey((threePowersKey + "_roleAuditadm")));
        return new ArrayList<>(Arrays.asList(roleAuditadm.split(",")));
    }

    public static List<String> getRoleSecadm() {
        String threePowersKey = CommonConstant.DATA_DICT_KEY + "insight_threePowers";
        String roleSecadm = String.valueOf(cacheUtils.getValueByKey((threePowersKey + "_roleSecadm")));
        return new ArrayList<>(Arrays.asList(roleSecadm.split(",")));
    }
}
